package cn.lanqiao.springboot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.UUID;

@Service
public class ArticleService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Transactional
    public synchronized void doLike(int articleId, int userId) {
        boolean isLike = false;
        //1、获得文章对应的点赞信息
        HashSet<Integer> articleUserSet = (HashSet<Integer>) redisTemplate.opsForHash().get("article:user", "article:" + articleId);
        //2、判断一下是点赞还是取消点赞
        if (articleUserSet == null) { // 新发表的文章
            isLike = true;
            articleUserSet = new HashSet<>();
        } else {
            if (!articleUserSet.contains(userId)) { //点赞列表中没有该用户
                isLike = true;
            }
        }
        //3、根据判断进行操作
        int delta = 0;
        if (isLike) {
            articleUserSet.add(userId);
            delta = 1; //总点赞数 +1
        } else {
            articleUserSet.remove(userId);
            delta = -1; //总点赞数 -1
        }
        redisTemplate.opsForHash().increment("article:likeCount", "article:" + articleId, delta);
        redisTemplate.opsForHash().put("article:user", "article:" + articleId, articleUserSet);
    }

    @Transactional
    public void buy(int goodsId, int userId) {
        String killId = "12345";
        synchronized (this) {
            //1、使用 userId和goodsId来判断该用户是否已经参与秒杀   userId:goodsId = orderId
            String orderId = (String) redisTemplate.opsForHash().get("kill:" + killId, userId + ":" + goodsId);
            if (orderId != null) {
                return;
            }
            int count = (Integer) redisTemplate.opsForValue().get("goods:" + goodsId);
            if (count <=0) {
              return;
            }
            //redis操作创建订单
            redisTemplate.opsForHash().put("kill:" + killId, userId + ":" + goodsId, UUID.randomUUID());
            //更新库存
            redisTemplate.opsForValue().increment("goods:" + goodsId, -1);
        }
    }

    public void createOrder(){
        //获得hash
        //遍历hash
        //向MQ中发送数据

    }
}
